﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Threading;
using IndustrialSmokeCalc.SmokeCalcWCF;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Maps.Toolkit;
using Microsoft.Phone.Shell;
using Microsoft.Devices;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;
using Telerik.Windows.Controls;
using HeaderedItemsControl = Telerik.Windows.Controls.Primitives.HeaderedItemsControl;

namespace IndustrialSmokeCalc
{
    public partial class Camera : PhoneApplicationPage
    {
        private PhotoCamera _cam;
        private double _canvasWidth;
        private double _canvasHeight;
        private int _timer = 0;
        private DispatcherTimer newTimer;

        public Camera()
        {
            InitializeComponent();            
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (Microsoft.Devices.Camera.IsCameraTypeSupported(CameraType.Primary))
            {
                _cam = new PhotoCamera(CameraType.Primary);
                _cam.Initialized += CamInitialized;
                _cam.CaptureImageAvailable += CamCaptureImageAvailable;

                //_cam.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(CamCaptureCompleted);
                viewfinderBrush.RelativeTransform = new CompositeTransform() { CenterX = 0.5, CenterY = 0.5, Rotation = 90 };
                //viewfinderBrush.Stretch = Stretch.None;
                viewfinderBrush.SetSource(_cam);
                //CameraButtons.ShutterKeyPressed += OnButtonFullPress;
            }
        }

        private void StartTimer()
        {
            _timer++;
            _cam.CaptureImage();

            newTimer = new DispatcherTimer();
            int interval = 60 / DataSingleton.Instance.SecondMeasurement;
            newTimer.Interval = TimeSpan.FromSeconds(interval);
            newTimer.Tick += OnTimerTick;
            newTimer.Start();
        }

        private void OnTimerTick(object sender, EventArgs e)
        {
            _timer++;
            _cam.CaptureImage();
            int total = DataSingleton.Instance.MinuteMeasurement*DataSingleton.Instance.SecondMeasurement;
            txtTitle.Text = String.Format("{0} / {1}", _timer, total);
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            if (_cam != null)
            {
                _cam.Dispose();
                _cam.Initialized -= CamInitialized;
                if(_timer > 0) newTimer.Stop();
            }
        }

        private double GetCameraAspectRatio()
        {
            IEnumerable<Size> resList = _cam.AvailableResolutions;
            Size res  = resList.ElementAt(1);

            return res.Width / res.Height;
        }

        private void CamInitialized(object sender, CameraOperationCompletedEventArgs e)
        {
            if (e.Succeeded)
            {
                Dispatcher.BeginInvoke(delegate()
                {//2048x1536
                    //_canvasWidth = Application.Current.Host.Content.ActualWidth;
                    //_canvasHeight = Application.Current.Host.Content.ActualHeight;//_canvasWidth * GetCameraAspectRatio();
                    //viewfinderCanvas.Width = _canvasWidth;
                    //viewfinderCanvas.Height = _canvasHeight;

                    //viewfinderCanvas.Width = Application.Current.Host.Content.ActualWidth;

                    Size res = _cam.AvailableResolutions.OrderByDescending(s => s.Width).First();
                    _cam.Resolution = res;
                    _cam.FlashMode = FlashMode.Off;
                    //MessageBox.Show(_cam.Resolution.Width + "x" + _cam.Resolution.Height);
                });
            }
        }


        private void CamCaptureImageAvailable(object sender, ContentReadyEventArgs e)
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                {
                    BitmapImage bmp = new BitmapImage();
                    bmp.SetSource(e.ImageStream);

                    WriteableBitmap bitmap = new WriteableBitmap(bmp);
                    DataSingleton.Instance.Picture = bitmap;
                    
                    e.ImageStream.Seek(0, SeekOrigin.Begin);

                    //MediaLibrary library = new MediaLibrary();
                    //library.SavePictureToCameraRoll("aaa", e.ImageStream);

                    OpacityMeasurement.GetOpacity(DataSingleton.Instance.Picture);
                    int x = _timer/DataSingleton.Instance.SecondMeasurement;
                    if (_timer % DataSingleton.Instance.SecondMeasurement == 0) x -= 1;
                    int y = _timer%DataSingleton.Instance.SecondMeasurement;
                    if (y == 0) y = DataSingleton.Instance.SecondMeasurement;
                    DataSingleton.Instance.MeasurementResult[x,y-1] = DataSingleton.Instance.RingelmannOpacity / 20;
                });                
            }
            finally
            {
                if (_timer == DataSingleton.Instance.MinuteMeasurement * DataSingleton.Instance.SecondMeasurement)
                {
                    //newTimer.Stop();
                    DataSingleton.Instance.FinishTime = DateTime.Now.ToString("HH:mm:ss");
                    Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/MeasurementResult.xaml", UriKind.Relative)));
                }
            }
        }

        private void CamCaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
        {
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
        }

        private void OnButtonFullPress(object sender, EventArgs e)
        {
            if (_cam != null)
            {
                try
                {
                    // Start image capture.
                    _cam.CaptureImage();
                }
                catch (Exception ex)
                {
                    this.Dispatcher.BeginInvoke(delegate()
                    {
                        // Cannot capture an image until the previous capture has completed.
                        MessageBox.Show(ex.Message);
                    });
                }
            }
        }

        private void btnCapture_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Start image capture.
                //_cam.CaptureImage();

                DataSingleton.Instance.StartTime = DateTime.Now.ToString("HH:mm:ss");

                StartTimer();
                btnCapture.IsEnabled = false;
            }
            catch (Exception ex)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // Cannot capture an image until the previous capture has completed.
                    MessageBox.Show(ex.Message);
                });
            }
        }
    }
}